package com.accompany.fragment.my.activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.accompany.R;
import com.accompany.api.bean.BankInfoBean;
import com.accompany.api.bean.VerBankCardNoBean;
import com.accompany.api.category.AddBlankCardCategory;
import com.accompany.api.presenter.AddBlankCardPresenter;
import com.accompany.base.BaseActivity;
import com.accompany.base.BaseBean;
import com.accompany.dialog.LoadingDialog;
import com.accompany.fragment.login.UserLoginActivity;
import com.accompany.main.ConstantStaticUrl;
import com.accompany.utils.CountDownTimerUtils;
import com.accompany.utils.EditTextChecked;
import com.accompany.utils.FullScreenUtils;
import com.accompany.utils.SPUtils;
import com.accompany.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 界面: 添加银行卡界面
 * company: 兰州丰荣信息科技有限公司
 * 创建时间: on 2022/2/25 15 ：16
 * 项目名称：yuanban
 */
public class AddBlankCardActivity extends BaseActivity implements TextWatcher, AddBlankCardCategory.View {
    @BindView(R.id.base_title)
    TextView mTitleMesg;
    @BindView(R.id.ed_yhkh)
    EditText mYhkh;
    @BindView(R.id.bryhk)
    EditText mBryhkh;
    @BindView(R.id.send_code)
    TextView mSendCode;
    @BindView(R.id.edit_name)
    EditText mEditName;
    @BindView(R.id.edit_ylsjh)
    EditText mEditPhone;
    @BindView(R.id.edit_code)
    EditText mEditCode;
    private BankInfoBean bankinfobean;
    private long mUserId;
    private AddBlankCardPresenter mPresenter;
    private String mCode;
    private String mToken;
    private boolean cardLength = false;
    private LoadingDialog loadingDialog  ;
    private boolean isCCB = false;

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_blank_card;
    }
    @Override
    public void initLayoutView() {

        onlyChinese();
        FullScreenUtils.getInstance().fullScreen(AddBlankCardActivity.this,true);
        mTitleMesg.setText("添加银行卡");
        listenerBankCard();
        mToken = (String) SPUtils.get(AddBlankCardActivity.this, ConstantStaticUrl.mToken, "");
        mYhkh.addTextChangedListener(this);
        mPresenter = new AddBlankCardPresenter(this);
        SetPersenter(mPresenter);
        SharedPreferences sharedPreferences = AddBlankCardActivity.this.getSharedPreferences("First", MODE_PRIVATE);
        mUserId = sharedPreferences.getLong(ConstantStaticUrl.userId, 0);
    }

    // 监听校验银行卡
    private void listenerBankCard() {

        mYhkh.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if(charSequence.length() > 16){
                    cardLength = true;
                }else {
                    cardLength = false;
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        mYhkh.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                    if(!hasFocus && cardLength){
                        //失去焦点
                        loadingDialog = new LoadingDialog(AddBlankCardActivity.this);
                        loadingDialog.show();
                        mPresenter.verBank(mToken,mYhkh.getText().toString().trim());
                    }
            }
        });
    }

    //只能输入汉字
    private void onlyChinese() {
        InputFilter inputFilter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                for (int i = start; i < end; i++) {
                    if (!EditTextChecked.isChinese(source.charAt(i))) {
                        ToastUtil.showToastINFO(AddBlankCardActivity.this,"只能输入汉字");
                        return "";
                    }
                }
                return null;
            }
        };
        mEditName.setFilters(new InputFilter[]{inputFilter});
    }

    @OnClick({R.id.base_back,R.id.send_code,R.id.submit_card})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.base_back:
                finishWitchAnimation();
                break;
            case R.id.send_code:
                String Mobile = mEditPhone.getText().toString().trim();
                if (Mobile.equals("")) {
                    ToastUtil.showToastINFO(AddBlankCardActivity.this, "请输入手机号码");
                } else {
                    CountDownTimerUtils mCountDownTimerUtils = new CountDownTimerUtils(mSendCode, 60000, 1000);
                    mCountDownTimerUtils.start();
                    mPresenter.getUserCode(Mobile);
                }
                break;
            case R.id.submit_card:
                String name = mEditName.getText().toString().trim();
                String mYinghangCard = mYhkh.getText().toString().trim();
                String mKaihuMc = mBryhkh.getText().toString().trim();
                String mMobile = mEditPhone.getText().toString().trim();
                String mEditCodes = mEditCode.getText().toString().trim();
                if (name.equals("")){
                    ToastUtil.showToastINFO(AddBlankCardActivity.this,"请输入姓名");
                    return;
                }else if (mYinghangCard.equals("")){
                    ToastUtil.showToastINFO(AddBlankCardActivity.this,"请输入银行卡信息");
                    return;
                }else if (mKaihuMc.equals("")){
                    ToastUtil.showToastINFO(AddBlankCardActivity.this,"请输入开户行名称");
                    return;
                }else if (mMobile.equals("")){
                    ToastUtil.showToastINFO(AddBlankCardActivity.this,"请输入银行绑定手机号");
                    return;
                }else if (mEditCodes.equals("")){
                    ToastUtil.showToastINFO(AddBlankCardActivity.this,"请输入验证码");
                    return;
                }else {
                    JSONObject result = new JSONObject();
                    try {
                        result.put("acdId", mUserId);
                        result.put("bankcardUsername", name);
                        result.put("acdPhone", mMobile);
                        result.put("bankName", mKaihuMc);
                        result.put("bankcardNo", mYinghangCard);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    mPresenter.addblank(mToken,result.toString());
                }
                break;

        }

    }
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}
    @Override
    public void afterTextChanged(Editable s) {
        String cardnum = mYhkh.getText().toString().trim();
        if (cardnum!=null && checkBankCard(cardnum)) {
            bankinfobean = new BankInfoBean(cardnum);
            mBryhkh.setText(bankinfobean.getBankName()+bankinfobean.getCardType());
        }
    }
    /**校验过程：
     1、从卡号最后一位数字开始，逆向将奇数位(1、3、5等等)相加。
     2、从卡号最后一位数字开始，逆向将偶数位数字，先乘以2（如果乘积为两位数，将个位十位数字相加，即将其减去9），再求和。
     3、将奇数位总和加上偶数位总和，结果应该可以被10整除。
     * 校验银行卡卡号
     */
    public static boolean checkBankCard(String bankCard) {
        if(bankCard.length() < 15 || bankCard.length() > 19) {
            return false;
        }
        char bit = getBankCardCheckCode(bankCard.substring(0, bankCard.length() - 1));
        if(bit == 'N'){
            return false;
        }
        return bankCard.charAt(bankCard.length() - 1) == bit;
    }

    /**
     * 从不含校验位的银行卡卡号采用 Luhn 校验算法获得校验位
     * @param nonCheckCodeBankCard
     * @return
     */
    public static char getBankCardCheckCode(String nonCheckCodeBankCard){
        if(nonCheckCodeBankCard == null || nonCheckCodeBankCard.trim().length() == 0
                || !nonCheckCodeBankCard.matches("\\d+")) {
            //如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeBankCard.trim().toCharArray();
        int luhmSum = 0;
        for(int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if(j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char)((10 - luhmSum % 10) + '0');
    }

    @Override
    public void getUserCode(BaseBean userCode) {
            if (userCode.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
                ToastUtil.showToastSUCCESS(AddBlankCardActivity.this, "验证码获取成功");
                mCode = userCode.getMsg();
            } else {
                ToastUtil.showToastINFO(AddBlankCardActivity.this, userCode.getMsg());
            }

    }

    @Override
    public void addblank(BaseBean baseBean) {
        if (baseBean.getCode()==ConstantStaticUrl.SUCCESS_CODE){
            ToastUtil.showToastINFO(AddBlankCardActivity.this,"银行卡信息添加成功");
            finish();
        }else {
            ToastUtil.showToastINFO(AddBlankCardActivity.this,baseBean.getMsg());
        }
    }

    @Override
    public void verBank(VerBankCardNoBean verBankCardNoBean) {
        loadingDialog.dismiss();
        if (verBankCardNoBean.getCode()==ConstantStaticUrl.SUCCESS_CODE){
            if (verBankCardNoBean.getData() != null  && verBankCardNoBean.getData().getBank().equals("CCB") &&
            verBankCardNoBean.getData().getCardType().equals("DC")){
//                ToastUtil.showToastINFO(AddBlankCardActivity.this,"银行卡号符合要求");
                 isCCB = true;
            }else {
                ToastUtil.showToastERROR(AddBlankCardActivity.this,"只能绑定建设银行储蓄卡");
                mYhkh.setText("");
                isCCB = false;
            }
        }else {
            ToastUtil.showToastINFO(AddBlankCardActivity.this,verBankCardNoBean.getMsg());
        }

    }

    @Override
    public void SetPersenter(Object persenter) {
    }
    @Override
    public void OnShowErrorMsg(String mErrorMsg) {
        ToastUtil.showToastERROR(AddBlankCardActivity.this,mErrorMsg);

    }


}
